//
//  WMH_MainTab1_ViewController.m
//  EpointFrame5
//
//  Created by AndLi on 15/4/21.
//  Copyright (c) 2015年 Epoint. All rights reserved.
//

#import "WMH_MainTab1_ViewController.h"
#import "HJObjManager.h"
#import "WMHMainItemView.h"
#import "EpointMainConfigModel.h"
#import "EpointBrowerViewController.h"
#import "EpointLoadMainConfigTask.h"
#import "EpointExtendAppConfig.h"
#import "EpointSettingViewController.h"
#import "EpointPlaySound.h"

#import "WMH_NewsDetail_ViewController.h"

#import "Task_GetInfoList.h"
#import "InfoListModel.h"
#import "MyScrollView.h"

#define LoadMainConfigTskId 1
#define User_GetInfo_TaskId 2
#define EpointRegistPushTokenTaskId 3
#define GenerationHeadImageTaskId 4

#define getFocusTitleTaskId 5
@interface WMH_MainTab1_ViewController ()<UIGestureRecognizerDelegate,UIScrollViewDelegate,onTouchDelegate>
{
    //根视图
    UIScrollView *mRootScrollView;
    
    UIView *uvScene;//头像
    HJObjManager *objMan;
    NSMutableArray *mainIconArray;
    UIView *uvMainIcon,*uvExtendIcon;
    UILabel *labExt;
    HJManagedImageV *headImgView;
    
    //焦点图标题列表
    NSMutableArray *focusTitleLists;
    
    int focusViewHeight;//焦点图高度
}

@property (retain, nonatomic) IBOutlet UILabel          *focusTitleLabel;//焦点图标题控件
@property (retain, nonatomic) IBOutlet UIPageControl    *pageControl;//焦点图下标控件
@property (retain, nonatomic) IBOutlet MyScrollView     *myScrollView;//焦点图控件
@end

@implementation WMH_MainTab1_ViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{
    if([[DBFrameService getConfigValue:@"mainChanged"] isEqualToString:@"1"]||
       [[DBFrameService getConfigValue:@"APPEXTENDCHANGED"]isEqualToString:@"1"])
    {
        [uvMainIcon removeFromSuperview];
        [self loadMainIconView];
        [DBFrameService setConfigValue:@"mainChanged" value:@"0"];
        
        [self loadExtendIconView];
        [DBFrameService setConfigValue:@"APPEXTENDCHANGED" value:@"0"];
    }
    
    [self startTask:@"User_GetInfo_Task" withParams:nil withTaskId:User_GetInfo_TaskId];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.title = @"新点微门户V5";
    
    [self initHJManage];
    
    [self initControls];
    
    mainIconArray = [EpointLoadMainConfigTask getPhoneArrByStore];
    
    [self loadMainIconView];
    [self loadExtendIconView];
    
    //监听图标更新
    //    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(update:) name:@"update" object:nil];
    
    //后台调用加载主界面模块配置数据库
    [self startTask:@"EpointLoadMainConfigTask" withParams:nil withTaskId:LoadMainConfigTskId];
    
    
    //获取缓存焦点图
    [self getCacheFocusInfo];
    //获取焦点图
    [self getFocusImgInfoTask];
    
}

//控件初始化
-(void)initControls
{
    
    _focusTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(4, 227, 250, 21)];
    [_focusTitleLabel setFont:[UIFont systemFontOfSize:13]];
    [_focusTitleLabel setTextColor:[UIColor whiteColor]];
    
    _pageControl     = [[UIPageControl alloc]initWithFrame:CGRectMake(248, 221, 73, 36)];
    
    
    //设置焦点图高度
    focusViewHeight = 250;
    //    if(IS_IPHONE_5){
    //        focusViewHeight = 287;
    //    }
    
    _myScrollView    = [[MyScrollView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, focusViewHeight)];
    
    _myScrollView.contentSize = CGSizeMake(1280, focusViewHeight);
    _myScrollView.delegate = self;
    _myScrollView.pagingEnabled = YES;
    _myScrollView.userInteractionEnabled = YES;
    _myScrollView.bounces = NO;
    _myScrollView.showsHorizontalScrollIndicator = NO;
    _myScrollView.showsVerticalScrollIndicator = NO;
    
    _pageControl.numberOfPages = 4;
    _pageControl.currentPage = 0;
    
    [self.customBackground setImage:[UIImage imageNamed:@"img_main_bg2"]];
    self.navigationController.navigationBarHidden = NO;
    //隐藏返回按钮
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = nil;
    
    [self.view setBackgroundColor:COLOR(237, 237, 237)];
    
    //增加一个滚动视图
    mRootScrollView = [[UIScrollView alloc]initWithFrame:self.getFullContentFrame];
    [self.view addSubview:mRootScrollView];
    
    [mRootScrollView addSubview:_myScrollView];
    [mRootScrollView addSubview:_focusTitleLabel];
    [mRootScrollView addSubview:_pageControl];
    
}

//初始化图片缓存管理器
-(void)initHJManage
{
    objMan = [[HJObjManager alloc] initWithLoadingBufferSize:20 memCacheSize:30];
    NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/imgcache/flickr/"] ;
    HJMOFileCache* fileCache = [[HJMOFileCache alloc] initWithRootPath:cacheDirectory];
    objMan.fileCache = fileCache;
    fileCache.fileCountLimit = 100;
    fileCache.fileAgeLimit = 60*60*24*30; //1 week
    [fileCache trimCacheUsingBackgroundThread];
}

//监听更新
-(void)update:(NSNotification*)notify
{
    NSString *tips = [notify.userInfo objectForKey:@"tips"];
    NSString *type = [notify.userInfo objectForKey:@"type"];
    
    if ([type isEqualToString:@"mail"]) {
        if (tips.intValue>0) {
            [self changeIconTips:1 tips:tips hidden:NO];
        }
        else
        {
            [self changeIconTips:1 tips:tips hidden:YES];
        }
        
    }
    if ([type isEqualToString:@"waithandler"]) {
        if (tips.intValue>0) {
            [self changeIconTips:0 tips:tips hidden:NO];
        }
        else
        {
            [self changeIconTips:0 tips:tips hidden:YES];
        }
    }
}

//图标tips更新
-(void)changeIconTips:(int)index tips:(NSString *)tips hidden:(BOOL)ishidden
{
    UIImageView *tipV  = [[[[[[uvMainIcon subviews]objectAtIndex:uvMainIcon.subviews.count-1] subviews]objectAtIndex:index]subviews]objectAtIndex:2];
    UILabel *lb = [[tipV subviews]objectAtIndex:0];
    if (tips.length>2) {
        tipV.frame = [WMHMainItemView getTipLongRect];
    }
    else
    {
        tipV.frame = [WMHMainItemView getTipShort];
    }
    lb.frame = tipV.bounds;
    lb.text = tips;
    tipV.hidden = ishidden;
}

#pragma mark ---------------------------------刷新---------------------------------
-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    if (taskId==LoadMainConfigTskId) {
        mainIconArray = (NSMutableArray*)obj;
        [self loadMainIconView];
        
        [self getFocusImgInfoTask];
    }
    else if (taskId==User_GetInfo_TaskId)
    {
        NSMutableArray *arr = (NSMutableArray*)obj;
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        
        NSString *mailTips = [listData objectAtIndex:0];
        NSString *dbTips = [listData objectAtIndex:1];
        
        //更新邮件图标数量
        if (mailTips.intValue>0) {
            [self changeIconTips:1 tips:mailTips hidden:NO];
        }
        else
        {
            [self changeIconTips:1 tips:mailTips hidden:YES];
        }
        //更新待办图标数量
        
        if (dbTips.intValue>0) {
            [self changeIconTips:0 tips:dbTips hidden:NO];
        }
        else
        {
            [self changeIconTips:0 tips:mailTips hidden:YES];
        }
    }
    else if (taskId==1234)
    {
        [self hideMBPHUD];
    }
    else if (taskId==GenerationHeadImageTaskId)
    {
        [objMan manage:headImgView];
    }
    else if(taskId == getFocusTitleTaskId){
        [self dealFocusTitleData:obj];
    }
}


#pragma mark 加载栏目
-(void)loadMainIconView
{
    int MainIconPanelNums = mainIconArray.count%3==0?mainIconArray.count/3:mainIconArray.count/3+1;
    CGFloat sceneBottomY = _myScrollView.frame.size.height+uvScene.frame.origin.y;
    [uvMainIcon removeFromSuperview];
    
    uvMainIcon = [self getIconView:mainIconArray rect:CGRectMake(0, sceneBottomY, AppWidth, 100*MainIconPanelNums)];
    [mRootScrollView addSubview:uvMainIcon];
    
    [mRootScrollView setContentSize:CGSizeMake(AppWidth, uvMainIcon.frame.origin.y+uvMainIcon.frame.size.height)];
    NSLog(@"svnum:%i",mRootScrollView.subviews.count);
}

-(UIView *)getIconView:(NSMutableArray *)iArr rect:(CGRect)rect
{
    int MainIconPanelNums = iArr.count%3==0?MainIconPanelNums = iArr.count/3:iArr.count/3+1;
    
    UIView *MainIconView = [[UIView alloc]initWithFrame:rect];
    NSString* displayLine =  @"1";//显示线
    if ([displayLine isEqualToString:@"1"]) {
        for (int i=0; i<MainIconPanelNums; i++) {
            
            //加载边框
            UIView *uvPanel = [[UIView alloc]initWithFrame:CGRectMake(0, i*106, AppWidth, 106)];
            uvPanel.backgroundColor = [UIColor clearColor];
            
            UIImageView *ivLineTop = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 1)];
            [ivLineTop setImage:[UIImage imageNamed:@"list_divider_line"]];
            [uvPanel addSubview:ivLineTop];
            
            UIImageView *ivLineBottom = [[UIImageView alloc]initWithFrame:CGRectMake(0, 106-1, AppWidth, 1)];
            [ivLineBottom setImage:[UIImage imageNamed:@"list_divider_line"]];
            [uvPanel addSubview:ivLineBottom];
            
            UIImageView *ivLine1 = [[UIImageView alloc]initWithFrame:CGRectMake(106, 0, 1, 106)];
            [ivLine1 setImage:[UIImage imageNamed:@"line_col"]];
            [uvPanel addSubview:ivLine1];
            
            UIImageView *ivLine2 = [[UIImageView alloc]initWithFrame:CGRectMake(140, 0, 1, 106)];
            [ivLine2 setImage:[UIImage imageNamed:@"line_col"]];
            //            [uvPanel addSubview:ivLine2];
            
            UIImageView *ivLine3 = [[UIImageView alloc]initWithFrame:CGRectMake(210, 0, 1, 106)];
            [ivLine3 setImage:[UIImage imageNamed:@"line_col"]];
            [uvPanel addSubview:ivLine3];
            
            if (i>0) {
                ivLineTop.hidden = YES;
            }
            [MainIconView addSubview:uvPanel];
        }
        
    }
    
    
    UIView *icoPanel = [[UIView alloc]initWithFrame:MainIconView.bounds];
    
    for (int i=0; i<iArr.count; i++) {
        
        EpointMainConfigModel *m = [iArr objectAtIndex:i];
        int icon_row = i/3;
        int icon_col = i%3;
        
        WMHMainItemView *icon = [[WMHMainItemView alloc]initWithFrame:CGRectMake(icon_col*106, 106*icon_row, 106,106) withHandler:^{
            //URL形式
            if ([m.type isEqualToString:@"2"]) {
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                [params setObject:m.dyUrl forKey:@"url"];
                [params setObject:m.modulename forKey:@"title"];
                EpointBrowerViewController *vc = [[EpointBrowerViewController alloc]init];
                vc.passParam = params;
                [self.navigationController pushViewController:vc animated:YES];
            }
            //原生界面跳转
            else if([m.type isEqualToString:@"1"])
            {
                
                NSData* aData = [m.paData dataUsingEncoding: NSUTF8StringEncoding];
                NSError *error;
                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                for (NSString *key in [json keyEnumerator]) {
                    [params setObject:[json objectForKey:key] forKey:key];
                }
                [params setObject:m.modulename forKey:@"title"];
                EpointPhoneViewController *c = [[NSClassFromString(m.launchclass) alloc]init];
                c.passParam = params;
                [self.navigationController pushViewController:c animated:YES];
            }
            //打开其他APP
            else if ([m.type isEqualToString:@"3"])
            {
                if (![[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:m.launchclass]]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.apkUrl]];
                }
                else
                {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.launchclass]];
                }
            }
        }];
        icon.lbTitle.text = m.modulename;
        [icoPanel addSubview:icon];
        
        icon.ivIcon.url = [NSURL URLWithString:[EpointBizTools getUrl:[NSString stringWithFormat:@"mobileconfig/mainimg/%@",m.iconUrl]]];
        [objMan manage:icon.ivIcon];
    }
    [MainIconView addSubview:icoPanel];
    return MainIconView;
}

-(void)loadExtendIconView
{
    NSArray *dataExtendArrQuery = [EpointExtendAppConfig findByCriteria:@""];
    NSMutableArray *dataExtendArr = [[NSMutableArray alloc]init];
    for (int i=0; i<dataExtendArrQuery.count; i++) {
        EpointExtendAppConfig *cg = [dataExtendArrQuery objectAtIndex:i];
        EpointMainConfigModel *em = [[EpointMainConfigModel alloc]init];
        em.moduleID = cg.moduleid;
        em.type = cg.type;
        em.isDefault = cg.isdefault;
        em.modulename = cg.modulename;
        em.position = cg.position;
        em.platform = cg.platform;
        em.dyUrl = cg.dyurl;
        em.paData = cg.padata;
        em.iconUrl = cg.iconurl;
        em.apkUrl = cg.apkurl;
        em.launchclass = cg.launchclass;
        em.packagename = cg.packagename;
        em.version = cg.version;
        em.tips = cg.tips;
        [dataExtendArr addObject:em];
    }
    
    if (dataExtendArr.count>0) {
        int uvExtentIconNums = dataExtendArr.count%3==0?dataExtendArr.count/3:dataExtendArr.count/3+1;
        CGFloat sceneBottomY = uvMainIcon.frame.size.height+uvMainIcon.frame.origin.y;
        [labExt removeFromSuperview];
        labExt = [[UILabel alloc]initWithFrame:CGRectMake(0, sceneBottomY, AppWidth, 40)];
        labExt.text = @"  扩展应用";
        labExt.backgroundColor = [UIColor clearColor];
        labExt.font = [UIFont systemFontOfSize:17];
        labExt.textColor = COLOR(128, 136, 149);
        labExt.shadowColor = [UIColor whiteColor];
        labExt.shadowOffset = CGSizeMake(0, 1);
        [mRootScrollView addSubview:labExt];
        [uvExtendIcon removeFromSuperview];
        uvExtendIcon = [self getIconView:dataExtendArr rect:CGRectMake(0, labExt.frame.origin.y+labExt.frame.size.height, AppWidth, 100*uvExtentIconNums)];
        [mRootScrollView addSubview:uvExtendIcon];
        [mRootScrollView setContentSize:CGSizeMake(AppWidth, uvExtendIcon.frame.origin.y+uvExtendIcon.frame.size.height)];
    }
    else
    {
        [labExt removeFromSuperview];
        [uvExtendIcon removeFromSuperview];
        [mRootScrollView setContentSize:CGSizeMake(AppWidth, uvMainIcon.frame.origin.y+uvMainIcon.frame.size.height+20)];
    }
    
}

#pragma mark ---------------------------------获取焦点图---------------------------------

//获取本地焦点图
-(void)getCacheFocusInfo{
    
    NSString *key = [NSString stringWithFormat:@"%@%@%@%@",NEWSLIST,CateNum_HeadNews,@"4",@"0"];
    
    NSString *LastHeadNewsListXML = [DBFrameService getCacheValue:key];
    
    focusTitleLists = [Task_GetInfoList getLists:LastHeadNewsListXML];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if (focusTitleLists.count==4) {
        
        InfoListModel *m = [focusTitleLists objectAtIndex:self.pageControl.currentPage];
        self.focusTitleLabel.text = m.Title;
        
        for (int i=0; i<focusTitleLists.count; i++) {
            InfoListModel *hnm = [focusTitleLists objectAtIndex:i];
            NSData *d = [ud objectForKey:hnm.InfoID];
            MyScrollView *ascrView = [[MyScrollView alloc] initWithFrame:CGRectMake(AppWidth * i, 0, AppWidth, focusViewHeight)];
            ascrView.image = [UIImage imageWithData:d];
            ascrView.dele = self;
            [self.myScrollView addSubview:ascrView];
        }
    }
}

//请求焦点图接口
-(void)getFocusImgInfoTask
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"0"              forKey:@"CurrentPageIndex"];
    [params setObject:@"4"              forKey:@"PageSize"];
    [params setObject:CateNum_HeadNews  forKey:@"CateNum"];
    [params setObject:@"1"              forKey:@"IsHeadNews"];
    [params setObject:@""               forKey:@"Title"];
    [self startTask:@"Task_GetInfoList" withParams:params withTaskId:getFocusTitleTaskId];
}

//处理返回数据
-(void)dealFocusTitleData:(NSObject *)obj{
    NSMutableArray *bd = (NSMutableArray *)obj;
    if ([[bd objectAtIndex:0]isEqualToString:@"1"])
    {
        focusTitleLists = [bd objectAtIndex:2];
        InfoListModel *m = [focusTitleLists objectAtIndex:self.pageControl.currentPage];
        self.focusTitleLabel.text = m.Title;
        
        for (int i=0; i<focusTitleLists.count; i++) {
            m = [focusTitleLists objectAtIndex:i];
            MyScrollView *ascrView = [[MyScrollView alloc] initWithFrame:CGRectMake(AppWidth * i, 0, AppWidth, focusViewHeight)];
            NSURL *imageUrl = [NSURL URLWithString:m.HeadNewsAttachUrl];
            //缓存
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            NSData *fileData = [NSData dataWithContentsOfURL:imageUrl];
            [ud setObject:fileData forKey:m.InfoID];
            ascrView.image = [UIImage imageWithData:fileData];
            ascrView.dele = self;
            [_myScrollView addSubview:ascrView];
        }
        
    }
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    _pageControl.currentPage = page;
    InfoListModel *m = [focusTitleLists objectAtIndex:self.pageControl.currentPage];
    self.focusTitleLabel.text = m.Title;
}

-(void)touchSV{
    
    InfoListModel *m = [focusTitleLists objectAtIndex:self.pageControl.currentPage];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:m.InfoID          forKey:@"InfoID"];
    [params setObject:CateNum_HeadNews  forKey:@"CateNum"];
    [params setObject:@"0"              forKey:@"IsNeedUrl"];
    WMH_NewsDetail_ViewController *view = [[WMH_NewsDetail_ViewController alloc]init];
    view.passParam = params;
    [self.navigationController pushViewController:view animated:YES];
}


@end


